import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/product.dart';

class ApiService {
  static const String baseUrl = 'http://124.221.18.218:9999';
  
  static Future<List<Product>> getProductList() async {
    try {
      print('[API] 开始请求商品列表...');
      print('[API] URL: $baseUrl/goods/list');
      
      final startTime = DateTime.now();
      final response = await http.post(
        Uri.parse('$baseUrl/goods/list'),
        headers: {'Content-Type': 'application/json'},
        body: json.encode({}),
      );
      final endTime = DateTime.now();
      final duration = endTime.difference(startTime).inMilliseconds;
      
      print('[API] 商品列表请求完成，耗时: ${duration}ms');
      print('[API] 状态码: ${response.statusCode}');
      print('[API] 响应体: ${response.body}');
      
      if (response.statusCode == 200) {
        final Map<String, dynamic> data = json.decode(response.body);
        if (data['code'] == 200 && data['data'] != null) {
          final List<dynamic> records = data['data']['records'] ?? [];
          print('[API] 成功获取商品列表，商品数量: ${records.length}');
          return records.map((item) => Product.fromJson(item)).toList();
        } else {
          print('[API] 业务错误 - code: ${data['code']}, message: ${data['message']}');
        }
      }
      throw Exception('Failed to load products - StatusCode: ${response.statusCode}');
    } catch (e) {
      print('[API] 请求商品列表失败: $e');
      print('[API] 错误类型: ${e.runtimeType}');
      throw e;
    }
  }
  
  static Future<String> getProductDescription(String productId) async {
    try {
      print('[API] 开始请求商品描述...');
      print('[API] URL: $baseUrl/goods/getGoodsDesc');
      print('[API] 商品ID: $productId');
      
      final startTime = DateTime.now();
      final requestBody = json.encode({'id': productId});
      print('[API] 请求体: $requestBody');
      
      final response = await http.post(
        Uri.parse('$baseUrl/goods/getGoodsDesc'),
        headers: {'Content-Type': 'application/json'},
        body: requestBody,
      );
      final endTime = DateTime.now();
      final duration = endTime.difference(startTime).inMilliseconds;
      
      print('[API] 商品描述请求完成，耗时: ${duration}ms');
      print('[API] 状态码: ${response.statusCode}');
      print('[API] 响应体: ${response.body}');
      
      if (response.statusCode == 200) {
        final Map<String, dynamic> data = json.decode(response.body);
        if (data['code'] == 200 && data['data'] != null) {
          final description = data['data'].toString();
          print('[API] 成功获取商品描述，长度: ${description.length}');
          return description;
        } else {
          print('[API] 业务错误 - code: ${data['code']}, message: ${data['message']}');
        }
      }
      throw Exception('Failed to load product description - StatusCode: ${response.statusCode}');
    } catch (e) {
      print('[API] 请求商品描述失败: $e');
      print('[API] 错误类型: ${e.runtimeType}');
      throw e;
    }
  }
}